package com.nunbey.lingxi.activities;

import com.nunbey.lingxi.R;
import com.nunbey.lingxi.apis.UserApi;
import com.nunbey.lingxi.lincat.activityinit.ActivityCollector;
import com.nunbey.lingxi.lincat.activityinit.BaseActivity;
import com.nunbey.lingxi.lincat.datastore.SharedPreferencesHelper;
import com.nunbey.lingxi.lincat.dialog.AlertDialogCreator;
import com.nunbey.lingxi.lincat.retrofitutil.RetrofitUtil;
import com.nunbey.lingxi.module.mode.user.UserAccount;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;

import org.json.JSONObject;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {
    final int reLoginFlag = 268468224;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //判断登录方式
        int startIntentFlag = this.getIntent().getFlags();
        //登录活动的启动方式并非是重新登录时再检验token
        if(startIntentFlag!=reLoginFlag)
           this.CheckLogin();
        //去掉标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    /**
     * @description 检测应用是否已经保存了用户的登录信息，如果保存了则直接登录不用再次登录
     */
    private void CheckLogin(){
        SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper();
        String token = sharedPreferencesHelper.getData(this,"userInfo","token");
        if(!token.equals("defaultValue")){
            IndexActivity.startMainActivity(this);
            this.finish();
        }
    }

    public static void startLoginActivity(Context context){
        context.startActivity(new Intent(context,LoginActivity.class));
    }

    /**
     * 按下返回键结束进程
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityCollector.getActivityCollector().killProcess();
    }

    /**
     * @description 用户登录
     */
    public void userLogin(View view){
        String email = ((EditText)findViewById(R.id.login_email)).getText().toString();
        String password = ((EditText)findViewById(R.id.login_password)).getText().toString();
        UserAccount userAccount = new UserAccount(email,password);
        UserApi userApi = (UserApi) RetrofitUtil.getApiInstance(UserApi.class);
        userApi.userLogin(userAccount).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    if(code==1000){
                        AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,"登录提示","该账号尚未注册，请先注册账号","确认",null);
                        confirmDialog.show();
                    }else if(code ==1003){
                        AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,"登录提示","账号或密码错误，请重新输入","确认",null);
                        confirmDialog.show();
                    }else if(code ==0){
                        JSONObject data = result.getJSONObject("data");
                        String token = data.getString("token");
                        SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper();
                        sharedPreferencesHelper.saveData(LoginActivity.this,"userInfo","token",token);
                        IndexActivity.startMainActivity(LoginActivity.this);
                        LoginActivity.this.finish();
                    }else {
                        Log.e(LoginActivity.class.toString(),"系统错误");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(LoginActivity.class.toString(),"系统错误");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(LoginActivity.class.toString(),"网络错误");
            }
        });


    }

    /**
     * 注册按钮跳转至注册页
     * @param view
     */
    public void navigateToSign(View view){

    }
}